package cn.laixueit.controller;

import cn.laixueit.commons.Utils;
import cn.laixueit.pojo.Teacher;
import cn.laixueit.service.TeacherService;
import cn.laixueit.service.impl.FileService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private FileService fileService;

    @PostMapping("/save")
    public String save(Teacher teacher){
        teacherService.save(teacher);
        return "redirect:page";
    }

    @GetMapping("/page")
    public String page(@RequestParam(defaultValue = "1")Integer start,
                       @RequestParam(defaultValue = "10")Integer size,
                       @ModelAttribute Teacher teacher,
                       Model model){
        PageInfo<Teacher> pageInfo =  teacherService.page(start,size,teacher);
        model.addAttribute("pageInfo",pageInfo);
        return "teacherList";
    }

    @GetMapping("/findById/{id}")
    public String findById(@PathVariable Integer id,Model model){
        Teacher teacher = teacherService.findById(id);
        model.addAttribute("teacher",teacher);
        return "teacherEdit";
    }

    @GetMapping("/removeById/{id}")
    public String removeById(@PathVariable Integer id){
        teacherService.removeById(id);
        return "redirect:/teacher/page";
    }

    @PostMapping("/update")
    public String update(@RequestParam("file")MultipartFile file,Teacher teacher,
                         HttpServletRequest request){

        if(file.getSize()!=0) {
            String newFileName = fileService.upLoadImg(file, request);
            if(!StringUtils.isEmpty(newFileName)){
                teacher.setImg(newFileName);
            }
        }
        teacherService.update(teacher);
        return "redirect:page";
    }





}
